
# Create your views here.
from django.shortcuts import render,HttpResponse
from django.conf.urls import patterns, url
from booking.models import Hotel
from booking.models import Room
from booking.models import Booking
from django.db import connection, transaction
from MySQLdb import *

# Create your views here.
def search(request):
    hotels = Hotel.objects.all()
    id_room=request.path.split('/')[2]
    context = {'HotelNmae': hotels,'IDroom':id_room}
#this line will go to the page search.html
    return render(request,'search.html', context)

def search_room(request):

    chkin=request.POST.get('chkin')
    chkout=request.POST.get('chkout')
    request.session['chick_in']=chkin
    request.session['chick_out']=chkout
    room = Room.objects.all()
    id_hotel=request.POST.get('select')
    hotels = Hotel.objects.filter(id=id_hotel)
    request.session['hotel_id']=id_hotel
    result = Room.objects.filter(hotel_id_id=id_hotel)
    cursor = connection.cursor() 
    cursor.execute(" select r.* "
                   " from booking_room as r "
                   " where r.hotel_id_id=%s"
                   " and r.id not in (select distinct res.room_id_id " 
                   " from booking_booking as res "
                   " where (res.start_date  between %s and %s) or (res.end_date  between %s and %s) )" 
                   
                                                                   ,[id_hotel,chkin,chkout,chkin,chkout]) 

    available = cursor.fetchall()
    context = {'Room': room,'IDhotel':id_hotel,'result':result,'hotels_all':hotels,'aval':available}
#this line will go to the page search.html
    return render(request,'search_room.html', context)

def booking_room(request):
    cin=request.session['chick_in']
    cout=request.session['chick_out']
    id_hotel=request.session['hotel_id']
    id_room=request.path.split('/')[3]
    comment=request.POST['comment']
    roomd=request.POST.get('room_id') #get the room_id from the post form

    #request.session['roomId']=room_id #put room id on the session
    context = {'cin':cin,'cout':cout,'roomid':roomd,'id_room':id_room,'id_hotel':id_hotel,'comment':comment}
    cursor = connection.cursor()
    query = "INSERT INTO booking_booking (hotel_id_id ,room_id_id,start_date,end_date,comment) VALUES (%s,%s,'%s','%s','%s')"%(id_hotel,id_room,cin,cout,comment)
    cursor.execute (query)
  
    return render(request,'booking_room.html',context)



